package com.foxmail.aroundme.boring.module.news.main.presenter;

import android.support.annotation.CheckResult;
import android.text.TextUtils;

import com.foxmail.aroundme.boring.BuildConfig;
import com.foxmail.aroundme.boring.base.present.BasePreImpl;
import com.foxmail.aroundme.boring.bean.entry.GIFEntry;
import com.foxmail.aroundme.boring.bean.entry.JokeEntry;
import com.foxmail.aroundme.boring.bean.entry.NewsEntry;
import com.foxmail.aroundme.boring.bean.entry.WeiXinEntry;
import com.foxmail.aroundme.boring.bean.newslist.NewsListBean;
import com.foxmail.aroundme.boring.module.news.main.module.INewsListInter;
import com.foxmail.aroundme.boring.module.news.main.view.INewsListView;
import com.foxmail.aroundme.boring.module.news.main.module.NewsListInterImpl;
import com.foxmail.aroundme.boring.utils.Config;
import com.foxmail.aroundme.boring.utils.m_enum.ChannelType;
import com.foxmail.aroundme.boring.utils.m_enum.DataLoadType;
import com.foxmail.aroundme.boring.utils.m_enum.RefreshType;
import com.foxmail.aroundme.boring.utils.m_enum.RequestErrorType;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gzl on 1/22/17.
 * <p>
 * List数据加载
 *
 *
 * 这个类主要是除了代表控制层。和其他的控制层不同的是，新闻控制层需要对数据进行处理{@link NewsListPreImpl#distributionType}。
 * 将{@link NewsListBean}取出来再封装，实现前台对不同数据的需求
 */

public class NewsListPreImpl extends BasePreImpl<INewsListView, List<NewsListBean>> implements INewsListPre {

    private INewsListInter<List<NewsListBean>> mNewsListInter;
    private String mChannelId;
    private boolean mIsRefresh = true;

    //unix时间戳，存储每次刷新时间
    private static String unixTime = "";

    public NewsListPreImpl(INewsListView view, String channelId) {
        super(view);

        mChannelId = channelId;
        mNewsListInter = new NewsListInterImpl(this);

    }

    @Override
    public void refreshData(@RefreshType.Refresh int type) {
        mIsRefresh = true;
        mSubscription = mNewsListInter.getDataFromNet(this, type, unixTime, mChannelId, true);
    }

    @Override
    public void loadMoreData(@RefreshType.Refresh int type) {
        mIsRefresh = false;
        mSubscription = mNewsListInter.getDataFromNet(this, type, unixTime, mChannelId, false);
    }


    @Override
    public void beforeRequest(@RefreshType.Refresh int type) {
        if (mView != null) {
            mView.showProgress(type);
        }
    }

    @Override
    public void requestError(String msg, @RequestErrorType.Request int error) {
        if (mView != null) {
            mView.hideProgress();

            if (error == RequestErrorType.REQUEST_ERROR) {
                mView.requestError(mIsRefresh ? DataLoadType.TYPE_REFRESH_FAIL : DataLoadType.TYPE_LOAD_MORE_FAIL);
            } else if (error == RequestErrorType.NET_ERROR) {
                mView.requestError(mIsRefresh ? DataLoadType.TYPE_REFRESH_NETWORK_ERROR : DataLoadType.TYPE_LOAD_MORE_NETWORK_ERROR);
            }
        }
    }

    @Override
    public void requestComplete() {
        if (mView != null) {
            mView.hideProgress();
        }
    }

    @Override
    public void requestSuccess(List<NewsListBean> newsListBeen, @ChannelType.Channel String channelId, boolean isCache) {

        if (mView == null) {
            if (BuildConfig.DEBUG) {
                KLog.e(Config.TAG, "mView == null");
            }
            return;
        }

        //只有笑话和GIF有unixTime
        if (TextUtils.equals(channelId, "10001") || TextUtils.equals(channelId, "10002")) {

            boolean check = getUnixTime(newsListBeen, channelId, isCache);
            //检查不通过返回数据是最新的
            if (!check) {
                mView.updateNewsList(null, mIsRefresh ? DataLoadType.TYPE_REFRESH_NO_DATA : DataLoadType.TYPE_LOAD_MORE_NO_DATA, channelId, isCache);
                return;
            }
        }



        List list = distributionType(newsListBeen, channelId);

        if (list == null) {
            mView.updateNewsList(null, mIsRefresh ? DataLoadType.TYPE_REFRESH_NO_DATA : DataLoadType.TYPE_LOAD_MORE_NO_DATA, channelId, isCache);
        } else {
            mView.updateNewsList(list, mIsRefresh ? DataLoadType.TYPE_REFRESH_SUCCESS : DataLoadType.TYPE_LOAD_MORE_SUCCESS, channelId, isCache);
        }


    }

    /**
     * 将返回的数据重新生成新的List保存
     *
     * @param newsList  数据集
     * @param channelId 频道ID
     * @return 返回List数据集
     */
    private List distributionType(List<NewsListBean> newsList, String channelId) {

        List list = null;
        switch (channelId) {
            case ChannelType.Joke:
                List<JokeEntry> jokeEntries = new ArrayList<>();
                for (NewsListBean newsListBean : newsList) {
                    //判空
                    if (TextUtils.isEmpty(newsListBean.jokeContent)
                            || TextUtils.isEmpty(newsListBean.jokeUpDateTime)
                            || TextUtils.isEmpty(newsListBean.jokeUnixTime)){
                        if (BuildConfig.DEBUG) {
                            KLog.e(Config.TAG, "JokeEntry is null");
                        }
                        return null;
                    }
                    JokeEntry jokeEntry = new JokeEntry();
                    jokeEntry.content = newsListBean.jokeContent;
                    jokeEntry.unixTime = newsListBean.jokeUnixTime;
                    jokeEntry.upDateTime = newsListBean.jokeUpDateTime;
                    jokeEntries.add(jokeEntry);
                }

                list = jokeEntries;
                break;


            case ChannelType.GIF:
                List<GIFEntry> gifEntries = new ArrayList<>();
                for (NewsListBean newsListBean : newsList) {
                    //判空
                    if (TextUtils.isEmpty(newsListBean.jokeContent)
                            || TextUtils.isEmpty(newsListBean.url)
                            || TextUtils.isEmpty(newsListBean.jokeUpDateTime)
                            || TextUtils.isEmpty(newsListBean.jokeUnixTime)){
                        if (BuildConfig.DEBUG) {
                            KLog.e(Config.TAG, "GIFEntry is null");
                        }
                        return null;
                    }
                    GIFEntry gifEntry = new GIFEntry();
                    gifEntry.content = newsListBean.jokeContent;
                    gifEntry.url = newsListBean.url;
                    gifEntry.unixTime = newsListBean.jokeUnixTime;
                    gifEntry.upDateTime = newsListBean.jokeUpDateTime;
                    gifEntries.add(gifEntry);
                }
                list = gifEntries;
                break;
            case ChannelType.WeiXin:
                List<WeiXinEntry> weiXinEntries = new ArrayList<>();
                for (NewsListBean newsListBean : newsList) {
                    //判空
                    if (TextUtils.isEmpty(newsListBean.url)
                            || TextUtils.isEmpty(newsListBean.title)
                            || TextUtils.isEmpty(newsListBean.WXSource)){
                        if (BuildConfig.DEBUG) {
                            KLog.e(Config.TAG, "WeiXinEntry is null");
                        }
                        return null;
                    }

                    WeiXinEntry weiXinEntry = new WeiXinEntry();
                    weiXinEntry.WXUrl = newsListBean.url;
                    weiXinEntry.WXFirstImg = newsListBean.WXFirstImg;
                    weiXinEntry.WXId = newsListBean.WXId;
                    weiXinEntry.WXMark = newsListBean.WXMark;
                    weiXinEntry.WXSource = newsListBean.WXSource;
                    weiXinEntry.WXTitle = newsListBean.title;
                    weiXinEntries.add(weiXinEntry);
                }
                list = weiXinEntries;
                break;
            //其他频道都是新闻
            // TODO: 2/19/17 后期可能会把新闻和其他频道单独分开
            default:

                List<NewsEntry> newsEntries = new ArrayList<>();
                for (NewsListBean newsListBean : newsList) {
                    //判空
                    if (TextUtils.isEmpty(newsListBean.newsAuthor_name)
                            || TextUtils.isEmpty(newsListBean.newsDate)
                            || TextUtils.isEmpty(newsListBean.title)
                            || TextUtils.isEmpty(newsListBean.url)){
                        if (BuildConfig.DEBUG) {
                            KLog.e(Config.TAG, "NewsEntry is null");
                        }
                        return null;
                    }

                    if (TextUtils.isEmpty(newsListBean.newsPicture1)) {
                        KLog.w("newsPicture1 == null");
                    }
                    if (TextUtils.isEmpty(newsListBean.newsPicture2)) {
                        KLog.w("newsPicture2 == null");
                    }
                    if (TextUtils.isEmpty(newsListBean.newsPicture3)) {
                        KLog.w("newsPicture3 == null");
                    }

                    NewsEntry newsEntry = new NewsEntry();
                    newsEntry.newsAuthor_name = newsListBean.newsAuthor_name;
                    newsEntry.newsCategory = newsListBean.newsCategory;
                    newsEntry.newsDate = newsListBean.newsDate;
                    newsEntry.newsPicture1 = newsListBean.newsPicture1;
                    newsEntry.newsPicture2 = newsListBean.newsPicture2;
                    newsEntry.newsPicture3 = newsListBean.newsPicture3;
                    newsEntry.newsTitle = newsListBean.title;
                    newsEntry.newsUniqueKey = newsListBean.newsUniquekey;
                    newsEntry.newsURL = newsListBean.url;
                    newsEntries.add(newsEntry);
                }
                list = newsEntries;
                break;
        }

        return list;
    }

    /**
     * 记录unixTime用来上拉加载
     *
     * @param newsListBeen 数据源
     * @param channelId    id号
     * @param isCache      是否是cache
     * @return 返回ture表示获取时间成功而且数据没有问题，如果返回失败表示数据有问题
     */
    private boolean getUnixTime(List<NewsListBean> newsListBeen, String channelId, boolean isCache) {

        //返回成功保存unixTime
        if (!isCache) {
            if (TextUtils.isEmpty(newsListBeen.get(0).jokeUnixTime)) {

                if (BuildConfig.DEBUG) {
                    KLog.e("unixTime is error");
                }
                return false;
            }

            //比较之前的时间和现在时间差别
            if (TextUtils.equals(unixTime, newsListBeen.get(0).jokeUnixTime)) {
                if (BuildConfig.DEBUG) {
                    KLog.e("unixTime is already loading");
                }
                return false;
            }

            unixTime = newsListBeen.get(0).jokeUnixTime + "";
            if (BuildConfig.DEBUG) {
                KLog.d("unixTime = " + unixTime);
            }
        }

        return true;

    }
}
